<template>
  <div class="giftPage">
    <div style="background-color: #fffcfa;padding-bottom: 10px">
      <!--页面标题-->
      <div class="gift-left-title">
        <h2>{{pageTitle}}</h2>
      </div>
      <div class="gift-title-line"></div>
      <!-- 页面按钮 -->
      <div class="gift-button-inputSearch">
        <div class="gift-div-button">
          <el-button type="primary" plain  class="gift-button" @click="dialogVisible = true">新增礼品</el-button>
          <el-button type="primary" plain  class="gift-button" @click="reviewReleaseGift">编辑礼品</el-button>
          <el-button type="primary" plain  class="gift-button" @click="updateGiftStatus">礼品下架</el-button>
        </div>
        <div class="input-search">
          <el-input style="width:20%" v-model="searchVal" placeholder="礼品名称搜索" @input="changeInputSearchByGiftName">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
      </div>
      <GiftTableList :tableDataList="tableData" :loadingBoolean="loadingBoolean" @changeData="handleTableChange"></GiftTableList>

      <!-- 数据分页 -->
      <div style="width: 100%;text-align: center; margin: 5px auto">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
      <!-- 新增 -->
      <el-dialog
        title="新增礼品"
        :visible.sync="dialogVisible"
        :before-close="closeAddGiftDialog">
        <el-form style="padding: 5px" :inline="true" class="el-demo" ref="addGift" :model="addGiftForm" :before-close="closeAddGiftDialog">
          <el-form-item style="" label="礼品名称" prop="giftname">
            <el-input v-model="addGiftForm.giftname"></el-input>
          </el-form-item>
          <el-form-item label="兑换所需积分" prop="giftintegral">
            <el-input v-model="addGiftForm.giftintegral" type="number"></el-input>
          </el-form-item>
          <el-form-item label="礼品展示图" prop="giftimg" style="display: none;">
            <el-input v-model="addGiftForm.giftimg" ></el-input>
          </el-form-item>
          <!--<el-form-item label="介绍详情">-->
          <UEditor :config=ueConfig id="addGiftUeditor" ref="addGiftUeditor" ></UEditor>
          <!--</el-form-item>-->
        </el-form>
        <span slot="footer" class="dialog-footer">
                <el-button @click="closeAddGiftDialog">取 消</el-button>
                <el-button type="primary" @click="addGiftSubmit">确定</el-button>
        </span>
      </el-dialog>

      <!-- 修改-->
      <el-dialog
        title="编辑礼品"
        :visible.sync="dialogFromVisible"
        :before-close="closeUpdateGiftDialog">
        <template>
          <el-form style="padding: 5px" :inline="true" class="el-demo" ref="updateGiftForm" :model="updateGiftForm">
            <el-form-item label="礼品编号">
              <el-input v-model="updateGiftForm.giftnum" type="number"></el-input>
            </el-form-item>
            <el-form-item style="" label="礼品名称">
              <el-input v-model="updateGiftForm.giftname" ></el-input>
            </el-form-item>
            <el-form-item label="兑换所需积分">
              <el-input v-model="updateGiftForm.giftintegral" type="number"></el-input>
            </el-form-item>
            <UEditor :config=ueConfig id="updateGiftUeditor" ref="updateGiftUeditor"></UEditor>
          </el-form>

        </template>
        <span slot="footer" class="dialog-footer">
              <el-button @click="dialogFromVisible = false">取 消</el-button>
              <el-button type="primary" @click="updateGiftSubmit">确 定</el-button>
      </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import UEditor from  '../../NavUeditor/NavUeditor.vue'
  import util from '../../../../Js/utils'
  import GiftTableList from '../GiftManagement/GiftTableList.vue'
  export default {
    data(){
      return {
        // 搜索存词
        searchVal:null,
        // 表单加载
        loadingBoolean:false,
        updateshujv:{
          id:'',
          giftflag:'',
        },
        giftname1:'',
        giftintegral1:'',
        loading: false,
//          页面标题
        pageTitle:'礼品管理',
//          当前页
        currentPage1: 1,
//        每页显示几条
        pageSize: 10,
//        总条目数
        total: 0,
//        新增
        dialogVisible: false,
//       修改
        dialogFromVisible: false,
//        table表的数据
        tableData: [],
//        新增表单的字段
        addGiftForm: {
          giftnum: null,//礼品编码
          giftname: null,//礼品名称
          giftintegral: null,//全积分兑换数值
          giftdetails:null,//礼品详情
          giftimg:null// 展示图
        },
        // 计时器
        setTimeOut:null,
//        修改
        updateGiftForm: {},
        tableDtaChecked:null,
        ueConfig: {
          //可以在此处定义工具栏的内容
          toolbars: [[
            'fullscreen',  '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
            'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
            'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'insertframe',  'webapp', 'pagebreak', 'template', 'background', '|',
            'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
            'print', 'preview', 'searchreplace', 'help', 'drafts'
          ]],
          zIndex:3000,
          autoHeightEnabled: false,
          autoFloatEnabled: true,
          elementPathEnabled : false,
          initialContent:'',   //初始化编辑器的内容,也可以通过textarea/script给值，看官网例子
          autoClearinitialContent:true, //是否自动清除编辑器初始内容，注意：如果focus属性设置为true,这个也为真，那么编辑器一上来就会触发导致初始化的内容看不到了
          initialFrameWidth: null,
          initialFrameHeight: 300,
          BaseUrl: '',
          UEDITOR_HOME_URL: 'static/ueditor/'
        },
      }
    },
    created(){
      // 页面初始加载礼品列表
      this.selectGiftListByPageNum(1)
    },
    methods: {
      // 礼品名称查询
      changeInputSearchByGiftName(searchValue){
        this.loadingBoolean = true;
        this.$http.post(
          this.$BASE_URL+'gift/selectbylike',
          {pageNum:1,pageSize:100000,giftName:searchValue},
          {emulateJSON:false}
        ).then(res => {
          let reqList = res.data;
          if(reqList.length>0) {
            for (let i = 0; i < reqList.length; i++) {
              if (reqList[i].giftflag === 0) {
                reqList[i]['giftstatus'] = '展示中'
              } else if (reqList[i].giftflag === 1) {
                reqList[i]['giftstatus'] = '已下架'
              }
            }
            this.tableData = reqList;
          }
          this.loadingBoolean = false
        },res => {
          console.error(res)
        })
      },
      // 修改礼品状态,下架
      updateGiftStatus(){
        if(!this.tableDataChecked){
          this.$notify.error({
            title: '操作错误',
            message: '请先选择一条数据,再进行下架处理'
          });
          return;
        }
        if(this.tableDataChecked.giftflag === 1){
          this.$notify.error({
            title: '操作错误',
            message: '该礼品已下架'
          });
          return;
        }
        this.$confirm('此操作将让该活动恢复待审核状态,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {
            giftflag:1,id:this.tableDataChecked.id
          };
          this.$http.post(
            this.$BASE_URL+'gift/updateflag',
            (params),{emulateJSON:false}
          ).then(res => {
            this.$message.success('礼品下架成功');
            this.selectGiftListByPageNum(1);
            this.currentPage = 1;
          },res => {
            this.$message.error(res.data.resMessage);
            console.error(res)
          })
        }).catch(()=>{

        });

      },
      // 分页查询礼品列表
      selectGiftListByPageNum(pageNum){
        let params = {
          pageNum:pageNum,pageSize:this.pageSize
        };
        this.loadingBoolean = true;
        this.$http.post(
          this.$BASE_URL+'/gift/selectbyorganizationid',
          params,{emulateJSON:false}
        ).then(res => {
          let reqList = res.data.list;
          if(reqList.length>0){
            for(let i = 0;i<reqList.length;i++){
              if(reqList[i].giftflag === 0){
                reqList[i]['giftstatus'] = '展示中'
              }else if(reqList[i].giftflag === 1){
                reqList[i]['giftstatus'] = '已下架'
              }
            }
            console.log(reqList);
            this.total = res.data.total;
            this.tableData = reqList;
            this.loadingBoolean = false
          }
        },res =>{
          this.loadingBoolean = false;
          console.error(res);
        })
      },
      // 新增礼品弹窗页面关闭 数据重置
      closeAddGiftDialog(done){
        this.$confirm('确认是否关闭？页面上的数据将不会被保留')
          .then(_ => {
            this.resetForm('addGift');
            this.addGiftForm.giftdetails = null;
            this.$refs.addGiftUeditor.setUEContent('<p>请输入内容</p>');
            this.dialogVisible = false;
            done();
          })
          .catch(_ => {});
      },
      // 修改页面弹窗关闭
      closeUpdateGiftDialog(done){
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
      },
      // 修改页面提交 gift/updategift
      updateGiftSubmit(){
        let resData = this.updateGiftForm;
        let contentHtml = this.$refs.updateGiftUeditor.getUEContent();
        resData.giftimg = util.getFirstImageByContentHtml(contentHtml);
        resData.giftdetails = contentHtml;
        resData.gifttime = util.formatTime(resData.gifttime);
        this.$http.post(
          this.$BASE_URL+'gift/updategift',
          (resData),{emulateJSON:true}
        ).then(res => {
          let resCode = res.data.code;
          if (resCode === 200){
            this.dialogFromVisible = false;
            this.$message.success('礼品编辑成功');
          }else {
            this.$message.error(res.data.resMessage);
          }
        },res => {
          console.error(res)
        })
      },
      /*确认上架*/
      fabu(){
        console.log("名字是:",this.tableDataChecked.num);
        console.log(this.$BASE_URL+'gift/updateflag')
        this.updateshujv.id=Number(this.tableDataChecked.num);
        this.updateshujv.giftflag=Number(0);
        console.log(this.updateshujv.id);
        console.log(this.updateshujv.giftflag);
        var _this = this;
        this.$http.post(
          this.$BASE_URL+'gift/updateflag',
          (_this.updateshujv),{emulateJSON:true}
        ).then((res)=>{
          console.log(res);
        },)
      },
//        表单内容被选中
      handleTableChange(e){
        this.tableDataChecked = e;
      },
//      礼品编辑按钮
      reviewReleaseGift(){
        if(!this.tableDataChecked){// 没有选中数据
          this.$notify.error({
            title: '操作错误',
            message: '请先选择一条数据,再进行编辑礼品'
          });
          return;
        }
        this.$http.post(
          this.$BASE_URL+'gift/selectbyid',
          {id:Number(this.tableDataChecked.id)},{emulateJSON:false}
        ).then(res => {
          let reqCode = res.data.code;
          let output = res.data.output;
          if(reqCode === 200){
            this.updateGiftForm = output;
            this.dialogFromVisible = true;
            this.setTimeout = setTimeout(()=>{// 富文本初始化赋值
              this.$refs.updateGiftUeditor.setUEContent(output.giftdetails);
              clearTimeout(this.setTimeout)
            },500);
          }else{
            this.$message.error('加载失败')
          }
        },res => {
          console.error(res)
        });

      },
      //删除按钮
      open2(sid) {
        this.$confirm('确定要下架此礼品吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.deletePost(sid),
            this.$message({
              type: 'success',
              message: '下架成功!',
            });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消下架'
          });
        });
      },
//      分页
      handleCurrentChange(val) {
        if (this.currentPage != val) {
          this.currentPage = val;
          this.talentsPost(val)
        }
      },
//      关闭弹窗
      handleClose11(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
      },
      // 新增礼品页面 确定点击 发生提交
      addGiftSubmit(){
        let resData = this.addGiftForm;
        let contentHtml  = this.$refs.addGiftUeditor.getUEContent();// 获取富文本html格式内容
        let firstImage = util.getFirstImageByContentHtml(contentHtml);
        resData.giftimg = firstImage;
        resData.giftdetails = contentHtml;
        this.$http.post(
          this.$BASE_URL+'gift/addgift',
          (resData),{emulateJSON:true}
        ).then(res => {
          let reqCode = res.data.code;
          if (reqCode === 200){
            this.dialogVisible = false;
            this.resetForm('addGift');
            this.addGiftForm.giftdetails = null;
            this.$refs.addGiftUeditor.setUEContent('<p>请输入内容</p>');
            this.selectGiftListByPageNum(1);
            this.currentPage = 1;
            this.$message.success('礼品'+res.data.resMessage)
          }else{
            this.$message.error('礼品添加失败');
            console.error('礼品添加失败',res)
          }
        },res => {
          console.error(res)
        });
      },
      // 表单重置
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
    },
    components:{
      UEditor,GiftTableList
    }
  }</script>

<style scoped>
  .giftPage{
    width: 100%;
    height:100%;
    background-color: #fffcfa;
  }
  .gift-left-title{
    text-align: left;
    padding: 10px 20px;
  }
  .gift-title-line{
    height:1px;
    width: 98%;
    margin: auto 1%;
    background-color: #ddd;
  }
  .gift-div-button{
    margin: 10px 0 10px 30px;
  }
  .gift-button{
    margin: 0 20px;
  }
  .gift-button-inputSearch{
    display: flex;
  }
  .input-search{
    width: 60%;
    text-align: right;
    margin: 10px 0;
  }
</style>
